#include "processmessage.h"
#include "mainconfig.h"
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include "somanage.h"
#include <string.h>

char  tx_buff[CLIENT_BUF_SIZE];

int ProcessPOST(char * pbuffer,char * pbuftx)
{
	struct requestinfo postreq;
	char * libname;char *cmd; char *ret;
	postreq.method=skip(&pbuffer," ");
	postreq.url=skip(&pbuffer," ");
	postreq.httpversion=skip(&pbuffer,"\r\n\r\n");
	libname=skip(&postreq.url,"/");
        skip(&pbuffer,"<cmd>");
        cmd=skip(&pbuffer,"</cmd>");
        ret=(char *)malloc(SE_RET_LEN);
	if(ret==NULL)
	return -1;

	char * strSoapH =("<?xml version=\"1.0\" encoding=\"utf-8\"?>"
			"<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"
			"<soap:Body>"
			"<runResponse xmlns=\"http://tempuri.org/\">"
			"<runResult>");
	char * 	strSoapL=("</runResult>"
			"</runResponse>"
			"</soap:Body>"
			"</soap:Envelope>");
        int length=strlen(strSoapH)+strlen(strSoapL)+strlen(ret);
	sprintf(pbuftx,"HTTP/1.1 200 OK\r\n"
			"Content-Type: text/xml; charset=utf-8\r\n"
			"Content-Length: %d\r\n\r\n%s%s%s",
			length,strSoapH,ret,strSoapL);
	free(ret);
	return 0;
}

int ProcessGET(char * pbuffer,char * txbuf)
{
        char * ret;
        char method[8]={0};
        char url[64]={0};
        char httpversion[16]={0};
        struct requestinfo getreq;
        getreq.method=skip(&pbuffer," ");       
        getreq.url=skip(&pbuffer," ");
        getreq.httpversion=skip(&pbuffer,"\r\n");
              
 //if url is someting like adc?wsdl return back the wsdl
	 if((ret=strchr (getreq.url,'?'))!=NULL)
	{
	        char * szStatusCode="200 OK";
	        char * contentType_="text/html";
		//char * szConnectionType="close";
		char * Servername_="Soap App Server embedded";
		//char * szDateTime;
		struct tm * tm_ptr;
		time_t the_time;
		char date[100];
		int length;//the length of wsdl
		tm_ptr=gmtime(&the_time);
		char*  wsdl;
	        
	    strftime(date,100,"%a, %d %b %Y %H:%M:%S GMT",tm_ptr);
	    skip(&getreq.url,"/");
	    char* libname=skip(&getreq.url,"?");
	   // char path[40]="";
	   // sprintf(path,"lib%s.so",libname);
	    wsdl=Get_wsdl_by_sname(libname);	    
	    length=strlen(wsdl);
	    sprintf(txbuf,"HTTP/1.0 %s\r\nDate:%s\r\nServer:%s\r\nAccept-Ranges:bytes\r\nContent-Length:%d\r\nConnection:%s\r\nContent-Type:%s\r\n\r\n%s",
			 			 	szStatusCode,date,Servername_,length,"close",contentType_,wsdl);
	    return 0;
	}
	// char * szMethod;
	// char * szFileName;
        // char * szFileExt;
	 char * szStatusCode="200 OK";
	 char * contentType_="text/html";
	 char * szConnectionType="close";
	 char * Servername_="Soap App Server embedded";
	 char * szNotFoundMessage;
	 char * szDateTime;
	 char * dir=HomeDir;
	 char path[60]="";
	 sprintf(path,"%s%s",dir,getreq.url);
	 struct tm * tm_ptr;
	 time_t the_time;
	 tm_ptr=gmtime(&the_time);
	 char date[100];
	 int length;//the length of readed file
	 strftime(date,100,"%a, %d %b %Y %H:%M:%S GMT",tm_ptr);
	 //read the answer web page
	    FILE *f;
	    int lengthActual=0;
	 	f = fopen(path, "r+b");
	 	if(f != NULL)
	 	{
	 		// get the  file size
	 		fseek(f, 0, SEEK_END);
	 		fgetpos(f, (fpos_t*)&lengthActual);
	 		fseek(f, 0, SEEK_SET);

	 		char *pBuf = malloc(lengthActual + 1);

	 		length = fread(pBuf, 1, (int)lengthActual, f);
	 		fclose(f);
	 		pBuf[(int)lengthActual]='\0';

	 		sprintf(txbuf,"HTTP/1.0 %s\r\nDate:%s\r\nServer:%s\r\nAccept-Ranges:bytes\r\nContent-Length:%d\r\nConnection:%s\r\nContent-Type:%s\r\n\r\n%s",
	 			 				 			szStatusCode,date,Servername_,length,"close",contentType_,pBuf);
	 	        return 0;
	 	}
	 	else
	 	{
	 		memset(path,0,sizeof(path));
	 		char *dir=HomeDir;
	 		sprintf(path,"%s/404.html",dir);
	 		f=fopen(path,"r+b");
	 		if(f!=NULL)
	 		{
	 			fseek(f,0,SEEK_END);
	 			fgetpos(f,&lengthActual);
	 			fseek(f,0,SEEK_SET);
	 			char *pbuf=malloc((int)lengthActual+1);
	 			length=fread(pbuf,1,(int)lengthActual,f);
	 			fclose(f);
	 			pbuf[lengthActual]='\0';
	 			szStatusCode="404 resource not found";
	 			sprintf(txbuf,"HTTP/1.0 %s\r\nDate:%s\r\nServer:%s\r\nAccept-Ranges:bytes\r\nContent-Length:%d\r\nConnection:%s\r\nContent-Type:%s\r\n\r\n%s",
	 				 			szStatusCode,date,Servername_,length,"close",contentType_,pbuf);
	 			free(pbuf);
	 			return 0;
	 		}
	 	}
        return -1;
}

//int   processmessage(void * pclient )
int   processmessage(int sockfd,char * workbuf,int recvbyte)
{
	printf("procemessage......\n");
	if(recvbyte>=HTTP_HEAD_LEN)
	{
		//printf("receive: %s\n",rx_buff);
		char head[HTTP_HEAD_LEN]="";
		int i=0;
	        memcpy(head,workbuf,3);
	        for(i=0;i<3;i++)
	    	head[i]=toupper(head[i]);
	        if(strcmp(head,"GET")==0)
	       {
		    	if(ProcessGET(workbuf,tx_buff)==0)
	                {
				send(sockfd,tx_buff,strlen(tx_buff),0);
				return 0;

	                }
	                else
	                {        
				return -1;
	                }
	    	
		}
		else
		{
				memset(head,0,sizeof(head));
				memcpy(head,workbuf,4);
				for(i=0;i<HTTP_HEAD_LEN;i++)
					head[i]=toupper(head[i]);

				if(strcmp(head,"POST")==0)
				{
					printf("get \"POST\" message\n");
					if(ProcessPOST(workbuf,tx_buff)!=0)
					return -1;
					send(sockfd,tx_buff,strlen(tx_buff),0);
					return 0;
				}
		}
	}
}

char *skip(char **buf, const char *delimiters) 
{
	  char *p, *begin_word, *end_word, *end_delimiters;

	  begin_word = *buf;
	  end_word = begin_word + strcspn(begin_word, delimiters);
	  end_delimiters = end_word + strspn(end_word, delimiters);

	  for (p = end_word; p < end_delimiters; p++) {
	    *p = '\0';
	  }
	  *buf = end_delimiters;
	  return begin_word;
}

